<?php

namespace app\admin\controller;

use app\common\controller\Adminbase;

use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
use think\Exception;

/**
 * 客源列管理
 */
class SysSource extends Adminbase
{

    /**
     * SourceModel模型对象
     * @var \app\admin\model\SourceModel
     */
    protected $modelClass = null;

    protected function initialize()
    {
        parent::initialize();
        $this->modelClass = new \app\admin\model\SourceModel;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Curd.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$page, $limit, $where, $sort, $order] = $this->buildTableParames();

            $list = $this->modelClass
                ->where(['member_id' => 0])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(
                    ['id', 'member_id', 'company_name', 'phone', 'status', 'weigh', 'create_time', 'update_time']
                );
            }

            $result = ["code" => 0, "count" => $list->total(), "data" => $list->items()];

            return json($result);
        }
        return $this->fetch();
    }


    public function import()
    {
        $params = $this->request->param();
        if ($params['path']) {
            $filePath = '.' . $params['path'];
            // 加载Excel文件
            $spreadsheet = IOFactory::load($filePath);
            $sheet = $spreadsheet->getActiveSheet();
            // 获取数据范围
            $info = $sheet->toArray();
            array_shift($info);
            try {
                $result = [];
                foreach ($info as $value) {
                    $data['member_id'] = 0;
                    $data['company_name'] = $value[0];
                    $data['phone'] = $value[1];
                    $data['create_time'] = time();
                    $data['update_time'] = time();
                    $result[] = $data;
                }
                Db::name('source')->insertAll($result);
                return json([
                    'code' => 1,
                    'msg' => '上传成功',
                ]);
            } catch (Exception $e) {
                return json([
                    'code' => 0,
                    'msg' => $e->getMessage(),
                ]);
            }
        }
    }


}
